#include "medicalserver.h"
#include <QDebug>

MedicalServer::MedicalServer(QObject *parent) : QTcpServer(parent) {
}

MedicalServer::~MedicalServer() {
    stopServer();
}

bool MedicalServer::startServer(const QString& host, quint16 port) {
    QHostAddress address;
    if (host == "0.0.0.0" || host.isEmpty()) {
        address = QHostAddress::Any;
    } else {
        address = QHostAddress(host);
    }
    
    if (listen(address, port)) {
        qDebug() << "服务器启动成功，监听地址:" << host << "端口:" << port;
        return true;
    } else {
        qDebug() << "服务器启动失败:" << errorString();
        return false;
    }
}

void MedicalServer::stopServer() {
    // 断开所有客户端连接
    for (ClientHandler* client : m_clients) {
        client->disconnectFromClient();
        client->deleteLater();
    }
    m_clients.clear();
    
    // 停止监听
    if (isListening()) {
        close();
        qDebug() << "服务器已停止";
    }
}

void MedicalServer::incomingConnection(qintptr socketDescriptor) {
    qDebug() << "新客户端连接:" << socketDescriptor;
    
    try {
        ClientHandler* client = new ClientHandler(socketDescriptor, this);
        connect(client, &ClientHandler::disconnected, this, &MedicalServer::onClientDisconnected);
        
        m_clients.append(client);
        client->start();
        
        qDebug() << "客户端处理器创建成功，当前连接数:" << m_clients.size();
    } catch (const std::exception& e) {
        qDebug() << "创建客户端处理器失败:" << e.what();
    } catch (...) {
        qDebug() << "创建客户端处理器失败: 未知异常";
    }
}

void MedicalServer::onClientDisconnected(ClientHandler* client) {
    qDebug() << "客户端断开连接";
    m_clients.removeOne(client);
    client->deleteLater();
}

